﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace WindowsFormsApplication1.FindFriends
{
    public class FindFriendsManager
    {
        public FindFriendsManager() { }

        private List<FindFriendsRequest> pendingRequests = new List<FindFriendsRequest>();

        public void sendFindFriendsRequests(ServerSocketData requestingServer, int friendsOfCharacterId, string xmlFriendIds)
        {
            FindFriendsRequest ffr = new FindFriendsRequest(requestingServer);
            ffr.friendsOfCharacterId = friendsOfCharacterId;

            //Get list of friend IDs we're going to query from the other world servers
            List<int> friendIdsToFind = new List<int>();
            StringReader sr = new StringReader(xmlFriendIds);
            XmlTextReader xmlReader = new XmlTextReader(sr);
            while (xmlReader.Read())
            {
                if (xmlReader.Name == "friend")
                    friendIdsToFind.Add(int.Parse(xmlReader.GetAttribute("id").ToString()));
            }
            ffr.friendIdsToFind = friendIdsToFind;

            //Add this request to the queue of pending requests
            lock (pendingRequests)
            {
                pendingRequests.Add(ffr);
            }

            //Send out the query to the other world servers
            ffr.sendRequests();
        }

        public void processFindFriendsResult(ServerSocketData fromServer, int friendsOfCharacterId, string xmlMessage)
        {
            lock (pendingRequests)
            {
                foreach (FindFriendsRequest ffr in pendingRequests)
                {
                    if (ffr.friendsOfCharacterId == friendsOfCharacterId)
                    {
                        ffr.processResult(fromServer, xmlMessage);
                        break;
                    }
                }
            }
        }

        public void completeRequest(FindFriendsRequest request)
        {
            lock (pendingRequests)
            {
                pendingRequests.Remove(request);
            }

            request.completeRequest();
        }
    }
}
